<?php
class Pelicula extends CI_Controller {

	// número de registros por página
	private $limit = 10;
	
	function __construct(){
                parent::__construct();
                // Your own constructor code
                //
                // load library
		$this->load->library(array('table'));
		
		// load helper
		$this->load->helper('url');
		
		// load model
		$this->load->model('peliculaModel','',TRUE);
	}
	
	function index($offset = 0){
		// offset
		$uri_segment = 3;
		$offset = $this->uri->segment($uri_segment);
		
		// load data
		$peliculas = $this->peliculaModel->get_paged_list($this->limit, $offset)->result();
		
		// generate pagination
		$this->load->library('pagination');
		$config['base_url'] = site_url('pelicula/index/');
 		$config['total_rows'] = $this->peliculaModel->count_all();
 		$config['per_page'] = $this->limit;
		$config['uri_segment'] = $uri_segment;
		$this->pagination->initialize($config);
		$data['pagination'] = $this->pagination->create_links();
		
		// generate table data
		$this->load->library('table');
		$this->table->set_empty("&nbsp;");
		$this->table->set_heading('Imagen', 'Titulo', 'Director', 'Clasificación', 'Nota', 'Calificar');
		$i = 0 + $offset;
		foreach ($peliculas as $pelicula){
			$this->table->add_row(++$i, $pelicula->TITULO, $pelicula->DIRECTOR, $pelicula->CLASIFICACION,
				anchor('pelicula/rating/'.$pelicula->id,'Rating',array('class'=>'rating')));
		}
		$data['table'] = $this->table->generate();
		
		// load view
		$this->load->view('peliculaList', $data);
	}
	
	function view($id){
		// set common properties
		$data['title'] = 'pelicula Details';
		$data['link_back'] = anchor('pelicula/index/','Back to list of peliculas',array('class'=>'back'));
		
		// get pelicula details
		$data['pelicula'] = $this->peliculaModel->get_by_id($id)->row();
		
		// load view
		$this->load->view('peliculaView', $data);
	}
	
	
	
	// validation fields
	function _set_fields(){
		$fields['id'] = 'id';
		$fields['name'] = 'name';
		$fields['gender'] = 'gender';
		$fields['dob'] = 'dob';
		
		$this->validation->set_fields($fields);
	}
	
	// validation rules
	function _set_rules(){
		$rules['name'] = 'trim|required';
		$rules['gender'] = 'trim|required';
		$rules['dob'] = 'trim|required|callback_valid_date';
		
		$this->validation->set_rules($rules);
		
		$this->validation->set_message('required', '* required');
		$this->validation->set_message('isset', '* required');
		$this->validation->set_error_delimiters('<p class="error">', '</p>');
	}
	
	// date_validation callback
	function valid_date($str)
	{
		if(!ereg("^(0[1-9]|1[0-9]|2[0-9]|3[01])-(0[1-9]|1[012])-([0-9]{4})$", $str))
		{
			$this->validation->set_message('valid_date', 'date format is not valid. dd-mm-yyyy');
			return false;
		}
		else
		{
			return true;
		}
	}
}
?>